import React, { useState, useEffect, FC, forwardRef, useImperativeHandle, MutableRefObject, useRef } from 'react'
import {
  Space, Input, Row, Image,
  Col, Avatar, Popover, Upload, Form
} from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'
import type { RcFile, UploadFile, UploadProps, UploadChangeParam } from 'antd/es/upload/interface'
import { useAppSelector, useAppDispatch } from '@/store'
import { updateUserInfo } from '@/store/login'
import * as api from '@/api'
import { IAvatarInfo, IAvatarListModel, IPasswordVerifyModel } from '@/models/user'
import XlModalFC from '@/components/xlmodal/xlmodal'
import XlButton from '../xlbutton/xlbutton'
import { IData, IResponseCodeType } from '@/models/common'
import util from '@/utils/util'
// @ts-ignore
import { sm2 } from 'sm-crypto'
import bgImg from "./images/bg.png"
import lockImg from "./images/lock.png"
import userImg from "./images/user.png"
import quitImg from "./images/quit.png"
import downloadImg from "./images/download.png"
import eyeShowImg from "./images/show.png"
import eyeHideImg from "./images/hide.png"
import 'antd/es/slider/style/css'
import "./userheader.scss"
export interface IUserHeader {
  ref?: React.ForwardedRef<IChildRef>
}
/**
 * 子组件暴露给父组件的函数
 */
export interface IChildRef {
  onClickOpenQuitModal: () => void
  onClickOpenUserInfoModal: () => void
  onClickOpenPasswordModal: () => void
}

export interface IViewModel {
  userInfoModalOpen: boolean
  userAvatarModalOpen: boolean
  passwordModalOpen: boolean
  quitModalOpen: boolean
  userInfoPopoverOpen: boolean
  avatarList: IAvatarInfo[]
  avatarCheckedIndex: number
  userNickName: string
  userInfoLoading: boolean
  passwordLoading: boolean
  oldPassword: string
  newPassword: string
  confirmPassword: string
  is_password_verify: string
  placeholder: string
}

const UserHeader: FC<IUserHeader> = forwardRef((props, ref) => {
  const navigate = useNavigate()
  const dispatch = useAppDispatch()
  const location = useLocation()
  const userInfo = useAppSelector((state) => state.login.userInfo)

  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      userInfoModalOpen: false,
      userAvatarModalOpen: false,
      passwordModalOpen: false,
      quitModalOpen: false,
      userInfoPopoverOpen: false,
      avatarList: [],
      avatarCheckedIndex: -1,
      userNickName: userInfo.user_nickname,
      userInfoLoading: false,
      passwordLoading: false,
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
      is_password_verify: '',
      placeholder: ""
    }
  })

  useImperativeHandle(ref, () => ({
    onClickOpenQuitModal: events.onClickOpenQuitModal,
    onClickOpenUserInfoModal: events.onClickOpenUserInfoModal,
    onClickOpenPasswordModal: events.onClickOpenPasswordModal,
  }))

  const events = {
    onOldPasswordChange(e: React.ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.oldPassword = e.target.value
      setData({ ...data })
    },
    onNewPasswordChange(e: React.ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.newPassword = e.target.value
      setData({ ...data })
    },
    onConfirmPasswordChange(e: React.ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.confirmPassword = e.target.value
      setData({ ...data })
    },
    onUserNickNameChange(e: React.ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.userNickName = e.target.value
      setData({ ...data })
    },
    onClickSelect(index: number) {
      const { ViewModel } = data
      if (index == ViewModel.avatarCheckedIndex) {
        return
      }
      ViewModel.avatarCheckedIndex = index
      setData({ ...data })
    },
    onUserInfoPopoverOpenChange(newOpen: boolean) {
      const { ViewModel } = data
      ViewModel.userInfoPopoverOpen = newOpen
      setData({ ...data })
    },
    async onClickOpenUserInfoModal() {
      const { ViewModel } = data
      if (ViewModel.avatarList.length == 0) {
        await methods.requestAvatarList()
      }
      ViewModel.userInfoModalOpen = true
      ViewModel.userInfoPopoverOpen = false
      let index = ViewModel.avatarList.findIndex(item => item.id == userInfo.avatar_id)
      ViewModel.avatarCheckedIndex = index
      ViewModel.userNickName = userInfo.user_nickname
      setData({ ...data })
    },
    async onClickOpenUserAvatarModal() {
      const { ViewModel } = data
      ViewModel.userAvatarModalOpen = true
      ViewModel.userInfoModalOpen = false
      setData({ ...data })
    },
    onClickOpenPasswordModal() {
      const { ViewModel } = data
      ViewModel.passwordModalOpen = true
      ViewModel.userInfoPopoverOpen = false
      ViewModel.oldPassword = ''
      ViewModel.newPassword = ''
      ViewModel.confirmPassword = ''
      setData({ ...data })
      methods.requestPasswordVerify()
    },
    onClickOpenQuitModal() {
      const { ViewModel } = data
      ViewModel.quitModalOpen = true
      ViewModel.userInfoPopoverOpen = false
      setData({ ...data })
    },
    onUpdateUserInfoOk() {
      const { ViewModel } = data
      if (ViewModel.userNickName == '') {
        util.alertTip("请输入用户昵称")
        return
      }
      ViewModel.userInfoLoading = true
      setData({ ...data })
      methods.requestEditPersonalInfo()
    },
    onUpdateUserInfoCancel() {
      const { ViewModel } = data
      ViewModel.userInfoModalOpen = false
      setData({ ...data })
    },
    onUpdateUserAvatarOk() {
      const { ViewModel } = data
      ViewModel.userAvatarModalOpen = false
      ViewModel.userInfoModalOpen = true
      setData({ ...data })
    },
    onUpdateUserAvatarCancel() {
      const { ViewModel } = data
      ViewModel.userAvatarModalOpen = false
      ViewModel.userInfoModalOpen = true
      setData({ ...data })
    },
    onUpdatePasswordOk() {
      const { ViewModel } = data
      const { oldPassword, newPassword, confirmPassword } = ViewModel
      const password_reg = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![~!@#$%^&*]+$)[0-9A-Za-z~!@#$%^&*]{8,16}$/
      if (oldPassword == '') {
        util.alertTip("请输入原密码")
        return
      }
      if (newPassword == '') {
        util.alertTip("请输入新密码")
        return
      }
      if (confirmPassword == '') {
        util.alertTip("请输入确认密码")
        return
      }
      // if (!password_reg.test(newPassword)) {
      //   util.alertTip("新密码为8-16位含字母、数字或符号的组合")
      //   return
      // }
      if (newPassword !== confirmPassword) {
        util.alertTip("两次密码输入不一致")
        return
      }
      ViewModel.passwordLoading = true
      setData({ ...data })
      methods.requestEditPassword()
    },
    onUpdatePasswordCancel() {
      const { ViewModel } = data
      ViewModel.passwordModalOpen = false
      ViewModel.passwordLoading = false
      setData({ ...data })
    },
    onQuitOk() {
      const { ViewModel } = data
      util.alertTip("退出账号成功")
      ViewModel.quitModalOpen = false
      setData({ ...data })
      events.gotoLoginPage()
    },
    onQuitCancel() {
      const { ViewModel } = data
      ViewModel.quitModalOpen = false
      setData({ ...data })
    },
    /**
     * 上传图片回调
     */
    onChangeUpload({ file, fileList, event }: UploadChangeParam) {
      if (file.status === 'done') {
        let { code, data: uplodaData, message } = file.response
        if (code == IResponseCodeType.Success) {
          const { ViewModel } = data
          ViewModel.avatarList = [...ViewModel.avatarList, { src: uplodaData.image_url, id: uplodaData.id }]
          ViewModel.avatarCheckedIndex = ViewModel.avatarList.length - 1
          setData({ ...data })
        } else {
          util.alertTip(message)
        }
      } else if (file.status === 'error') {
        util.alertTip("上传失败")
        // const reader = new FileReader()
        // reader.readAsDataURL(file.originFileObj as RcFile)
        // reader.onload = () => {
        //   const { ViewModel } = data
        //   ViewModel.avatarList = [...ViewModel.avatarList, reader.result as string]
        //   setData({ ...data })
        // }
      } else if (file.status == 'uploading') {

      }
    },
    onClickOpenXlAssistantModal() {
      
    },
    async gotoLoginPage() {
      let tenant_id = localStorage.getItem('tenant_id') || ''
      localStorage.clear()
      localStorage.setItem('tenant_id', tenant_id)
      navigate(`/login?tenant_id=${tenant_id}`, { replace: true, state: { from: location } })
    },
  }

  const methods = {
    async requestPasswordVerify() {
    
    },
    async requestAvatarList() {
      
    },
    async requestEditPersonalInfo() {
      
    },
    async requestEditPassword() {
     
    },

    renderEyeImg(src: string) {
      return <Image src={src} preview={false} style={{ cursor: "pointer" }} />
    },
    renderPage() {
      return (
        <>
          <Popover
            placement='bottomRight'
            overlayClassName='userinfoPopover'
            open={data.ViewModel.userInfoPopoverOpen}
            onOpenChange={events.onUserInfoPopoverOpenChange}
            getPopupContainer={(triggerNode: HTMLElement): HTMLElement => document.getElementById("userinfo-wrap") as HTMLElement}
          >
            <Row align='middle' wrap id='userinfo-wrap' className='topHeaderUserinfoWrap'>
              <Col className='useravatar'>
                <Avatar src={'http://192.168.3.165:9109/enterprise/v1.0/get_image?code=1267485628581281792&type=avatar&token=4C30FF75100942B7239BCBCD50920187F1FCDFD6F9048F9DA2878815DDD342DC&time=1729056247723'} alt="avatar" size={40}></Avatar>
              </Col>
              <Col>
                <Space direction='vertical' align='center' size={0}>
                  <Row className='username'>测试账号</Row>
                  <Row className='userlabel'>管理员</Row>
                </Space>
              </Col>
            </Row>

          </Popover>
          {/* 修改个人信息弹出框 */}
          <XlModalFC
            title="修改个人信息"
            open={data.ViewModel.userInfoModalOpen}
            onOk={events.onUpdateUserInfoOk}
            onCancel={events.onUpdateUserInfoCancel}
            okText='确认'
            cancelText='取消'
            className='userinfoModal'
            confirmLoading={data.ViewModel.userInfoLoading}
          >
            <Row className='userinfoModalContent'>
              <Row className='title'>头像</Row>
              <Row className='useravatar-upload' justify='center'>
                <Avatar src={data.ViewModel.avatarCheckedIndex == -1 ? userInfo.user_avatar : data.ViewModel.avatarList[data.ViewModel.avatarCheckedIndex].src} size={160} />
              </Row>
              <Row className='updateAvatarBtn'><XlButton type='link' block onClick={events.onClickOpenUserAvatarModal}>修改头像</XlButton></Row>
              <Row className='title'>昵称</Row>
              <Input placeholder='请输入昵称' allowClear value={data.ViewModel.userNickName} onChange={events.onUserNickNameChange}></Input>
            </Row>
          </XlModalFC>

          {/* 修改头像弹出框 */}
          <XlModalFC
            title="修改头像"
            open={data.ViewModel.userAvatarModalOpen}
            onOk={events.onUpdateUserAvatarOk}
            onCancel={events.onUpdateUserAvatarCancel}
            footer={[
              <Row justify='space-between' key='updateUserAvatarFooter' align='middle'>
                

                <Row align='middle'>
                  <XlButton type='default' onClick={events.onUpdateUserAvatarCancel}>
                    取消
                  </XlButton>
                  <XlButton type='primary' onClick={events.onUpdateUserAvatarOk}>
                    确定
                  </XlButton>
                </Row>
              </Row>
            ]}
            className='userinfoModal'
          >
            <Row className='userAvatarModalContent' gutter={[16, 16]} wrap >
              {
                data.ViewModel.avatarList.map((item, index) => {
                  if (index == data.ViewModel.avatarCheckedIndex) {
                    return <Col key={index} onClick={() => events.onClickSelect(index)}>
                      <Avatar src={item.src} size={50} className='active' />
                    </Col>
                  } else {
                    return <Col key={index} onClick={() => events.onClickSelect(index)}>
                      <Avatar src={item.src} size={50} />
                    </Col>
                  }
                })
              }
            </Row>
          </XlModalFC>

          {/* 修改密码弹出框 */}
          <XlModalFC
            title="修改密码"
            open={data.ViewModel.passwordModalOpen}
            onOk={events.onUpdatePasswordOk}
            onCancel={events.onUpdatePasswordCancel}
            okText='确认'
            cancelText='取消'
            className='userinfoModal'
            confirmLoading={data.ViewModel.passwordLoading}
          >
            <Form>
              <Row className='userinfoModalContent'>
                <Row className='title'>原密码</Row>
                <Row className='input-wrap'>
                  <Input.Password
                    placeholder='请输入原密码'
                    allowClear
                    autoComplete='off'
                    maxLength={16}
                    iconRender={(visible) => visible ? methods.renderEyeImg(eyeShowImg) : methods.renderEyeImg(eyeHideImg)}
                    value={data.ViewModel.oldPassword} onChange={events.onOldPasswordChange}
                  />
                </Row>
                <Row className='title'>新密码</Row>
                <Row className='input-wrap'>
                  <Input.Password
                    placeholder={data.ViewModel.is_password_verify == '1' ? data.ViewModel.placeholder : '请输入新密码'}
                    allowClear
                    autoComplete='off'
                    maxLength={16}
                    iconRender={(visible) => visible ? methods.renderEyeImg(eyeShowImg) : methods.renderEyeImg(eyeHideImg)}
                    value={data.ViewModel.newPassword} onChange={events.onNewPasswordChange}
                  />
                </Row>
                <Row className='title'>确认新密码</Row>
                <Row className='input-wrap'>
                  <Input.Password
                    placeholder={data.ViewModel.is_password_verify == '1' ? data.ViewModel.placeholder : '请再次输入新密码'}
                    allowClear
                    autoComplete='off'
                    maxLength={16}
                    iconRender={(visible) => visible ? methods.renderEyeImg(eyeShowImg) : methods.renderEyeImg(eyeHideImg)}
                    value={data.ViewModel.confirmPassword} onChange={events.onConfirmPasswordChange}
                  />
                </Row>
              </Row>
            </Form>
          </XlModalFC>

          {/* 退出账号弹出框 */}
          <XlModalFC
            title="退出账号"
            open={data.ViewModel.quitModalOpen}
            onOk={events.onQuitOk}
            onCancel={events.onQuitCancel}
            okText='确认'
            cancelText='取消'
            className='userinfoModal'
          >
            <Row className='userinfoModalContent'>
              <Row className='title'>您确认退出当前账号吗？</Row>
            </Row>
          </XlModalFC>
        </>
      )
    }
  }

  return methods.renderPage()
})

export default UserHeader
